import React from 'react';
import {
  Button,
  CssBaseline,
  TextField,
  FormControlLabel,
  Checkbox,
  Link,
  Grid,
  Typography,
  Container,
  makeStyles,
  FormHelperText,
} from '@material-ui/core';
import { useForm, Controller } from 'react-hook-form';
import { connect } from 'react-redux';

import { useHistory } from 'react-router-dom';
import { login } from '../../store/actions';

import { signUp } from '../../api/actions/user';

const useStyles = makeStyles((theme) => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(3),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
  },
}));

function SignUp(props) {
  const classes = useStyles();
  const history = useHistory();
  const {
    handleSubmit,
    control,
    getValues,
    formState: { errors },
  } = useForm();
  const { userLogin } = props;

  const handleSignUp = async (d) => {
    const res = await signUp(d);
    if (res.code === 0) {
      const userInfo = {
        token: res.data.token,
        ...res.data.userInfo,
      };
      window.localStorage.setItem('userInfo', JSON.stringify(userInfo));
      userLogin(userInfo);
      history.push('/');
    }
  };
  const handleError = (e) => {
    console.log(e);
  };
  const nameHelperText = () => errors.name && errors.name.type === 'required' && '请输入昵称';
  const phoneHelperText = () => (errors.phone && errors.phone.type === 'required' && '请输入手机号')
    || (errors.phone && errors.phone.type === 'pattern' && '请输入正确的手机格式');
  const mailHelperText = () => errors.mail && errors.mail.type === 'required' && '请输入邮箱';
  const passwordHelperText = () => errors.password && errors.password.type === 'required' && '请输入密码';
  const rePasswordHelperText = () => (errors.rePassword
      && errors.rePassword.type === 'required'
      && '请再次确认密码')
    || (errors.rePassword
      && errors.rePassword.type === 'validate'
      && '两次密码输入不一致');
  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Typography component="h1" variant="h5">
          注册
        </Typography>
        <form
          className={classes.form}
          noValidate
          onSubmit={handleSubmit(handleSignUp, handleError)}
        >
          <Grid container spacing={2}>
            <Grid item xs={12}>
              <Controller
                name="name"
                control={control}
                defaultValue=""
                rules={{ required: true }}
                render={({ field }) => (
                  <TextField
                    error={Boolean(errors && errors.name)}
                    variant="outlined"
                    fullWidth
                    id="name"
                    label="昵称"
                    helperText={nameHelperText()}
                    autoComplete="name"
                    {...field}
                  />
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <Controller
                name="phone"
                control={control}
                rules={{ required: true, pattern: /^1[3-9]\d{9}$/ }}
                defaultValue=""
                render={({ field }) => (
                  <TextField
                    error={Boolean(errors && errors.phone)}
                    variant="outlined"
                    fullWidth
                    id="phone"
                    label="手机号"
                    helperText={phoneHelperText()}
                    autoComplete="phone"
                    {...field}
                  />
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <Controller
                name="mail"
                control={control}
                rules={{ required: true }}
                defaultValue=""
                render={({ field }) => (
                  <TextField
                    error={Boolean(errors && errors.mail)}
                    variant="outlined"
                    fullWidth
                    id="mail"
                    label="邮箱"
                    helperText={mailHelperText()}
                    autoComplete="mail"
                    {...field}
                  />
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <Controller
                name="password"
                control={control}
                rules={{ required: true }}
                defaultValue=""
                render={({ field }) => (
                  <TextField
                    error={Boolean(errors && errors.password)}
                    helperText={passwordHelperText()}
                    variant="outlined"
                    fullWidth
                    id="password"
                    type="password"
                    label="密码"
                    autoComplete="password"
                    {...field}
                  />
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <Controller
                name="rePassword"
                control={control}
                rules={{
                  required: true,
                  validate: (d) => getValues('password') === d,
                }}
                defaultValue=""
                render={({ field }) => (
                  <TextField
                    error={Boolean(errors && errors.rePassword)}
                    helperText={rePasswordHelperText()}
                    variant="outlined"
                    fullWidth
                    id="rePassword"
                    type="password"
                    label="确认密码"
                    autoComplete="rePassword"
                    {...field}
                  />
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <Controller
                name="allowExtra"
                control={control}
                rules={{ required: true }}
                defaultValue={false}
                render={({ field }) => (
                  <FormControlLabel
                    control={
                      <Checkbox value="allowExtra" color="primary" {...field} />
                    }
                    label="我同意用户使用协议"
                  />
                )}
              />
              <FormHelperText error={Boolean(errors.allowExtra)}>
                请勾选用户使用协议
              </FormHelperText>
            </Grid>
          </Grid>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
          >
            注册
          </Button>
          <Grid container justify="flex-end">
            <Grid item>
              <Link href="/signIn" variant="body2">
                已有账号? 去登陆
              </Link>
            </Grid>
          </Grid>
        </form>
      </div>
    </Container>
  );
}

const mapDispatchToProps = (dispatch) => ({
  userLogin: (userInfo) => dispatch(login(userInfo)),
});

export default connect(null, mapDispatchToProps)(SignUp);
